<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提问时间" prop="consultationTime">
        <el-date-picker clearable
                        v-model="queryParams.consultationTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择提问时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="解答时间" prop="answerTime">
        <el-date-picker clearable
                        v-model="queryParams.answerTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择解答时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="orderId"/>

      <!-- 问题描述列 -->
      <el-table-column label="问题描述" align="center" prop="description" width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
              scope.row.description.length > 20 ? scope.row.description.substring(0, 10) + '...' : scope.row.description
            }}</span>
          <el-button
            v-if="scope.row.description.length > 20"
            size="mini"
            type="text"
            @click="handleSeeMore(scope.row)">
            查看更多
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="提问方式" align="center" prop="consultationType"/>
      <el-table-column label="患者姓名" align="center" prop="patientName"/>
      <el-table-column label="提问时间" align="center" prop="consultationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.consultationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解答时间" align="center" prop="answerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.answerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:order:edit']"
          >查看详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSeeMore(scope.row)"
            v-hasPermi="['system:order:remove']"
          >回答
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 查看详情弹窗 -->
    <el-dialog :title="'问题描述详情'" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form1" label-width="80px">
        <!-- 问题描述（只读） -->
        <el-form-item label="问题描述" prop="description">
          <el-input v-model="form1.description" type="textarea" readonly/>
        </el-form-item>

        <!-- 新增文本输入框 -->
        <el-form-item label="回答内容">
          <el-input v-model="form1.additionalInfo" type="textarea" placeholder="请输入回答内容"/>
        </el-form-item>

        <!-- 追问按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleFollowUp">回答</el-button>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
<!--    分页插件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改问诊订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名"/>
        </el-form-item>
        <el-form-item label="提问时间" prop="consultationTime">
          <el-date-picker clearable
                          v-model="form.consultationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择提问时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解答时间" prop="answerTime">
          <el-date-picker clearable
                          v-model="form.answerTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择解答时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog title="订单及患者详情" :visible.sync="detailDialogVisible" width="600px" append-to-body>
      <el-form ref="detailForm" :model="detailForm" label-width="120px" label-position="left">
        <!-- 订单信息 -->
        <el-form-item label="订单编号">
          <el-input v-model="detailForm.orderId" readonly />
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input v-model="detailForm.description" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="提问方式">
          <el-input v-model="detailForm.consultationType" readonly />
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="detailForm.patientName" readonly />
        </el-form-item>
        <el-form-item label="提问时间">
          <el-input v-model="detailForm.consultationTime" readonly />
        </el-form-item>
        <el-form-item label="解答时间">
          <el-input v-model="detailForm.answerTime" readonly />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-input v-model="detailForm.orderStatus" readonly />
        </el-form-item>
        <el-form-item label="医生编号">
          <el-input v-model="detailForm.doctorId" readonly />
        </el-form-item>
        <el-form-item label="回答内容">
          <el-input v-model="detailForm.answerContent" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-input v-model="detailForm.paymentMethod" readonly />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="detailForm.orderAmount" readonly />
        </el-form-item>

        <!-- 患者信息 -->
        <el-form-item label="身份证号">
          <el-input v-model="detailForm.idCard" readonly />
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="detailForm.gender" readonly />
        </el-form-item>
        <el-form-item label="出生日期">
          <el-input v-model="detailForm.birthDate" readonly />
        </el-form-item>
        <el-form-item label="体重 (kg)">
          <el-input v-model="detailForm.weight" readonly />
        </el-form-item>
        <el-form-item label="过敏史">
          <el-input v-model="detailForm.allergyHistory" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="既往病史">
          <el-input v-model="detailForm.medicalHistory" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="肝功能">
          <el-input v-model="detailForm.liverFunction" readonly />
        </el-form-item>
        <el-form-item label="肾功能">
          <el-input v-model="detailForm.kidneyFunction" readonly />
        </el-form-item>
        <el-form-item label="备孕/怀孕/哺乳状态">
          <el-input v-model="detailForm.pregnancyStatus" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetailDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/service/order";
import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/service/patient"
import { listDoctor, getDoctor, delDoctor, addDoctor, updateDoctor} from "@/api/service/doctor"
export default {
  name: "Order",
  data() {
    return {
      dialogVisible1: false,
      detailDialogVisible: false, // 详情弹窗控制
      form2: {
        description: ''
      },
      detailForm: {
        orderId: '',
        description: '',
        consultationType: '',
        patientName: '',
        consultationTime: '',
        answerTime: '',
        orderStatus: '',
        doctorId: '',
        answerContent: '',
        paymentMethod: '',
        orderAmount: '',
        idCard: '',
        gender: '',
        birthDate: '',
        weight: '',
        allergyHistory: '',
        medicalHistory: '',
        liverFunction: '',
        kidneyFunction: '',
        pregnancyStatus: ''
      },
      // 控制弹窗显示
      dialogVisible: false,
      // 表单数据
      form1: {
        description: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问诊订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        description: null,
        consultationType: null,
        patientName: null,
        consultationTime: null,
        answerTime: null,
        orderStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        description: [
          {required: true, message: "问题描述不能为空", trigger: "blur"}
        ],
        consultationType: [
          {required: true, message: "提问方式不能为空", trigger: "change"}
        ],
        patientName: [
          {required: true, message: "患者姓名不能为空", trigger: "blur"}
        ],
        consultationTime: [
          {required: true, message: "提问时间不能为空", trigger: "blur"}
        ],
        orderStatus: [
          {required: true, message: "订单状态不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 详情按钮操作
    handleDetail(row) {
      // 填充订单信息
      this.detailForm.orderId = row.orderId;
      this.detailForm.description = row.description;
      this.detailForm.consultationType = row.consultationType;
      this.detailForm.patientName = row.patientName;
      this.detailForm.consultationTime = this.parseTime(row.consultationTime, '{y}-{m}-{d} {h}:{i}');
      this.detailForm.answerTime = this.parseTime(row.answerTime, '{y}-{m}-{d} {h}:{i}');
      this.detailForm.orderStatus = row.orderStatus;
      this.detailForm.doctorId = row.doctorId || '未分配';
      this.detailForm.answerContent = row.answerContent || '暂无回答';
      this.detailForm.paymentMethod = row.paymentMethod || '未支付';
      this.detailForm.orderAmount = row.orderAmount || '0.00';

      // 模拟从患者表获取数据（需替换为实际 API 调用）
      this.fetchPatientDetail(row.patientName);
      this.detailDialogVisible = true;
    },

    // 从患者表获取详情（需替换为实际 API 调用）
    fetchPatientDetail(patientName) {
      // 假设通过 patientName 查询患者表数据，实际应调用后端 API
      // 这里用静态数据模拟，替换为真实数据
      this.detailForm.idCard = '123456789012345678';
      this.detailForm.gender = '男';
      this.detailForm.birthDate = '1990-05-15';
      this.detailForm.weight = '65.50';
      this.detailForm.allergyHistory = '无';
      this.detailForm.medicalHistory = '无';
      this.detailForm.liverFunction = '正常';
      this.detailForm.kidneyFunction = '正常';
      this.detailForm.pregnancyStatus = '无';
    },

    // 关闭详情弹窗
    closeDetailDialog() {
      this.detailDialogVisible = false;
      this.detailForm = {
        orderId: '',
        description: '',
        consultationType: '',
        patientName: '',
        consultationTime: '',
        answerTime: '',
        orderStatus: '',
        doctorId: '',
        answerContent: '',
        paymentMethod: '',
        orderAmount: '',
        idCard: '',
        gender: '',
        birthDate: '',
        weight: '',
        allergyHistory: '',
        medicalHistory: '',
        liverFunction: '',
        kidneyFunction: '',
        pregnancyStatus: ''
      };
    },
    // 现有方法...
    parseTime(time, format) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return format
        .replace('{y}', year)
        .replace('{m}', month)
        .replace('{d}', day)
        .replace('{h}', hours)
        .replace('{i}', minutes);
    },
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },

    // 点击查看更多
    handleSeeMore(row) {
      this.form1.description = row.description;
      this.dialogVisible = true;
    },

    // 追问按钮
    handleFollowUp() {
      this.$modal.confirm('确认进行回答吗？').then(() => {
        // 在这里可以进行追问的操作，比如发送请求
        this.$modal.msgSuccess('回答成功');
      });
    },
    /** 查询问诊订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        description: null,
        consultationType: null,
        patientName: null,
        consultationTime: null,
        answerTime: null,
        orderStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加问诊订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改问诊订单";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除问诊订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
